package com.offlinerssreader.view;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONException;

import com.offlinerssreader.controller.ActionResponse;
import com.offlinerssreader.controller.ORRController;
import com.offlinerssreader.controller.ReturnableResponse;

/**
 * Servlet implementation class ApiUser
 */
public class ApiUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private ServletContext context = null;
	private ORRController controller = null;
	
	@Override
	public void init() {
		this.context = this.getServletContext();
		this.controller = (ORRController) this.context.getAttribute("controller");
		if (this.controller == null) {
			this.controller = new ORRController();
			this.context.setAttribute("controller", this.controller);
		}
	}

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ApiUser() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doRequest(request, response);
	}

	protected void doRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter writer = response.getWriter();
		Integer userId;
		
		String call = request.getParameter("call");
		ReturnableResponse rtrn = new ActionResponse("nothing", true, "no msg", null);
		HttpSession session = request.getSession(true);
		
		if (call == null) {
			rtrn = new ActionResponse("", false, "No call identifier found", null);
		} else {
			userId = (Integer)session.getAttribute("userId");

			// Creating a new user
			if (call.equals("new")) {
				rtrn = this.controller.addUser(request.getParameter("mail"), 
						request.getParameter("firstName"), 
						request.getParameter("lastName"), 
						request.getParameter("password"));
				if (rtrn.getStatus()) {
					if (userId != null) {
						session.invalidate();
						session = request.getSession(true);
					}
					session.setAttribute("userId", (Integer)rtrn.getData());
				}
				
			// Authenticating via sent session ID
			} else if (call.equals("authenticate")) {
				if (userId != null) {
					rtrn = new ActionResponse(call, true, "Authentication cached", null);
				} else {
					rtrn = new ActionResponse(call, false, "Authentication not cached", null);
				}
			
			
			} else if (call.equals("getFeeds")) {
				if (userId != null) {
					rtrn = this.controller.getUserFeeds(userId);
				} else {
					rtrn = new ActionResponse(call, false, "Session not available", null);
				}

			} else if (call.equals("getAllItems")) {
				if (userId != null) {
					int cache = Integer.parseInt(request.getParameter("cache"));
					try {
						if (cache == 0) {
								rtrn = this.controller.getFeedAllItems(userId, false);
						} else {
							rtrn = this.controller.getFeedAllItems(userId, true);
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} else {
					rtrn = new ActionResponse(call, false, "Session not available", null);
				}
				
			// Activly logging in, if session is available, we're overriding it
			} else if (call.equals("login")){
				rtrn = this.controller.login(request.getParameter("username"), 
						request.getParameter("password"));
				if (rtrn.getStatus()) {
					if (userId != null) {
						session.invalidate();
						session = request.getSession(true);
					}
					session.setAttribute("userId", (Integer)rtrn.getData());
				}
			
			// Logging out
			} else if (call.equals("logout")) {
				session.invalidate();
			} else {
				rtrn = new ActionResponse(call, false, "Unsupported call in this API", null);
			}
		}
		try {
			writer.print(rtrn.toJson());
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
}
